# backend\models\followup_log.py
from datetime import datetime, timedelta
from backend.infrastructure.database import db

def get_beijing_time():
    """返回东八区当前时间"""
    return datetime.utcnow() + timedelta(hours=8)

class FollowupRecordLog(db.Model):
    __tablename__ = "followup_record_logs"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    record_id = db.Column(db.Integer, nullable=False, comment="随访记录ID")
    student_id = db.Column(db.Integer, nullable=False, comment="学生ID")
    action = db.Column(db.String(20), nullable=False, comment="操作类型：edit/delete")
    operator = db.Column(db.String(50), nullable=True, comment="操作人")
    old_content = db.Column(db.Text, nullable=True, comment="操作前内容（JSON字符串）")
    new_content = db.Column(db.Text, nullable=True, comment="操作后内容（JSON字符串）")
    # 修改：直接用 datetime.now()，不再加8小时
    created_at = db.Column(db.DateTime, default=datetime.now)

    def to_dict(self):
        # 返回东八区时间字符串
        created_at = self.created_at + timedelta(hours=8) if self.created_at and self.created_at.tzinfo is None else self.created_at
        return {
            "id": self.id,
            "record_id": self.record_id,
            "student_id": self.student_id,
            "action": self.action,
            "operator": self.operator,
            "old_content": self.old_content,
            "new_content": self.new_content,
            # 直接输出本地时间字符串
            "created_at": self.created_at.isoformat() if self.created_at else "",
        }

    # === 统一日志服务标准方法 ===
    @classmethod
    def log_create(cls, record, operator='系统', ip_address=None):
        """记录创建操作日志"""
        try:
            from backend.services.unified_log_service import log_service
            import json
            
            log = cls(
                record_id=record.id,
                student_id=record.student_id,
                action='CREATE',
                operator=operator,
                old_content='{}',  # 创建时无旧内容
                new_content=log_service.serialize_content(record.to_dict())
            )
            return log
        except Exception as e:
            print(f"记录创建日志失败: {e}")
            return None
    
    @classmethod
    def log_update(cls, record, old_data, operator='系统', ip_address=None):
        """记录更新操作日志"""
        try:
            from backend.services.unified_log_service import log_service
            import json
            
            log = cls(
                record_id=record.id,
                student_id=record.student_id,
                action='UPDATE',
                operator=operator,
                old_content=log_service.serialize_content(old_data),
                new_content=log_service.serialize_content(record.to_dict())
            )
            return log
        except Exception as e:
            print(f"记录更新日志失败: {e}")
            return None
    
    @classmethod
    def log_delete(cls, record, operator='系统', ip_address=None):
        """记录删除操作日志"""
        try:
            from backend.services.unified_log_service import log_service
            import json
            
            log = cls(
                record_id=record.id,
                student_id=record.student_id,
                action='DELETE',
                operator=operator,
                old_content=log_service.serialize_content(record.to_dict()),
                new_content='{}'  # 删除后无内容
            )
            return log
        except Exception as e:
            print(f"记录删除日志失败: {e}")
            return None
    
    @classmethod
    def log_restore(cls, record_id, student_id, old_data, restored_data, operator='系统', ip_address=None):
        """记录恢复操作日志"""
        try:
            from backend.services.unified_log_service import log_service
            import json
            
            log = cls(
                record_id=record_id,
                student_id=student_id,
                action='RESTORE',
                operator=operator,
                old_content=log_service.serialize_content(old_data),  # 恢复前状态
                new_content=log_service.serialize_content(restored_data)  # 恢复后状态
            )
            return log
        except Exception as e:
            print(f"记录恢复日志失败: {e}")
            return None
